package org.fly.jingwei.util;

import java.math.BigInteger;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization bigdata
 * @website https://www.jielongping.com
 * @date 2020/5/30 9:21 上午
 * @since 1.0
 */
public class KettleEncrypt {
    private static final int RADIX = 16;
    private static final String SEED = "0933910847463829827159347601486730416058";

    public static void main(String[] args) {
        String x = decryptPassword("Encrypted 2be98afc86aa7f2e4cb1aa265cd86aac8");
        System.out.println(x);
        String cluster = encryptPassword("cluster");
        System.out.println(cluster);
    }


    public static String decryptPassword(String encryptedFromKettle) {
        return decryptPasswordIn(encryptedFromKettle.replace("Encrypted ", ""));
    }


    public static String encryptPassword(String password) {
        if (password == null) {
            return "";
        }
        if (password.length() == 0) {
            return "";
        }

        BigInteger biPassword = new BigInteger(password.getBytes());

        BigInteger biR0 = new BigInteger(SEED);
        BigInteger biR1 = biR0.xor(biPassword);

        return biR1.toString(RADIX);
    }

    private static String decryptPasswordIn(String encrypted) {
        if (encrypted == null) {
            return "";
        }
        if (encrypted.length() == 0) {
            return "";
        }

        BigInteger biConfuse = new BigInteger(SEED);

        try {
            BigInteger biR1 = new BigInteger(encrypted, RADIX);
            BigInteger biR0 = biR1.xor(biConfuse);

            return new String(biR0.toByteArray());
        } catch (Exception e) {
            return "";
        }
    }

}
